#include "Simulation.h"

static wxSemaphore	Sema;
static void* Tick(void *T)
{
	static int i=0;
	Sema.Post();
	i++;
	if(i == 250)
	{
		i = 0;
		Sema.Post();
		Sema.Post();
		Sema.Post();
		Sema.Post();
		Sema.Post();
		Sema.Post();
	}
	return NULL;
}

Simulation::Simulation(void):Instrument()
{
	Resolution = 1;
	DigitalOffset = 2048;
	DigitalMax	=	4096;
	DigitalMin	=	0;

	Labels[0] = wxString::Format(wxT("Rampa"));
	Labels[1] = wxString::Format(wxT("1Hz"));
	Labels[2] = wxString::Format(wxT("5Hz"));
	Labels[3] = wxString::Format(wxT("10Hz"));
	Labels[4] = wxString::Format(wxT("15Hz"));
	Labels[5] = wxString::Format(wxT("20Hz"));
	Labels[6] = wxString::Format(wxT("25Hz"));
	Labels[7] = wxString::Format(wxT("50Hz"));
	MyName = _("SIMULATION");
	
	pTimer		=	new timer(4,NULL,&Tick,NULL);
	Initialize(8,256,5);
}

Simulation::~Simulation(void)
{
	if(pTimer != NULL)	delete pTimer;
}

void* Simulation::Entry(void)
{
	bool	SynchOk = false;
	int		read,SemaRet;

	SampleStruct	Signal;
	memset(&Signal,0,sizeof(Signal));
	Signal.Data.DataLen	=	Channels;
	memset(&Signal,0,sizeof(Signal));

	read = 0;
	Esci = false;
	while(!Esci)
	{
		SemaRet = Sema.WaitTimeout(50);
		if(SemaRet !=wxSEMA_TIMEOUT && IsRunning)
		{
			read++;
			if(read >= 8000) read = 0;
			memset(&Signal,0,sizeof(Signal));
			Signal.Data.DataLen	=	Channels;
			if(read < 2000)
			{
				Signal.Data.Signal[0] = 4096-read*2;
			}else
			{
				if( read < 6000)
				{
					Signal.Data.Signal[0] = 96;
				}else 
				{
					Signal.Data.Signal[0] = 96+ 2*(read - 6000);
				}
			}

			Signal.Data.Signal[1] =  2048 + 500 * sinf(6.28f/256.0f	*	1	*(float)read);
			Signal.Data.Signal[2] =  2048 + 500 * sinf(6.28f/256.0f	*	5	*(float)read);
			Signal.Data.Signal[3] =  2048 + 500 * sinf(6.28f/256.0f	*	10	*(float)read);
			Signal.Data.Signal[4] =  2048 + 500 * sinf(6.28f/256.0f	*	15	*(float)read);
			Signal.Data.Signal[5] =  2048 + 500 * sinf(6.28f/256.0f	*	20	*(float)read);
			Signal.Data.Signal[6] =  2048 + 500 * sinf(6.28f/256.0f	*	25	*(float)read);//50Hz
			Signal.Data.Signal[7] =  2048 + 500 * sinf(6.28f/256.0f	*	50	*(float)read);//70Hz
			for(int i=10;i<Channels;i++)
			{
				//float r = rand()*2048;
				Signal.Data.Signal[i]= 2048 + rand() *2048/RAND_MAX;
			}
			PutSample(&Signal);
		}
	}
	return 0;
}

void Simulation::StartDevice(wxString FileName,wxString FilePath,bool File)
{
	Instrument::StartDevice(FileName,FilePath,File);
	IsRunning	=	true;
	pTimer->start(PERIODIC);
}

void Simulation::StopDevice(void)
{
	IsRunning	=	false;
	Instrument::StopDevice();
	pTimer->stop();
}

int Simulation::OpenPort(const char *PortCom, const char *OpenVal2, const char *OpenVal3)
{

	return 1;
}
